package de.vogella.gae.java.todo.dao;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import de.vogella.gae.java.todo.model.Word;

public class DaoWords {

	private static DaoWords instance;
	
	public static DaoWords getInstance(){
		if (instance == null)
			instance = new DaoWords();
		return instance;
	}
	
	private static final Logger log = Logger.getLogger(DaoWords.class.getName());
	
	public List<Word> listWords() {
		EntityManager em = EMFService.get().createEntityManager();
		// Read the existing entries
		Query q = em.createQuery("select m from Word m");
		List<Word> todos = q.getResultList();
		log.info("Probando logs");
		
		return todos;
	}

	public void add(String userId, String summery, String description,
			String url) {
		synchronized (this) {
			EntityManager em = EMFService.get().createEntityManager();
			Word todo = new Word(userId, summery, description, url);
			em.persist(todo);
			em.close();
		}
	}

	public List<Word> getWords(String userId) {
		EntityManager em = EMFService.get().createEntityManager();
		Query q = em.createQuery("select t from Word t where t.author = :userId");
		q.setParameter("userId", userId);
		List<Word> todos = q.getResultList();
		return todos;
	}

	public void remove(long id) {
		EntityManager em = EMFService.get().createEntityManager();
		try {
			Word todo = em.find(Word.class, id);
			em.remove(todo);
		} finally {
			em.close();
		}
	}
}